package com.crm.smartmachine.ui.receive

import android.media.AudioAttributes
import android.media.SoundPool
import android.os.Bundle
import com.cheng.library.common.clickNoRepeat
import com.cheng.library.common.toast
import com.cheng.library.utils.Param
import com.crm.smartmachine.R
import com.crm.smartmachine.base.SmartBaseFragment
import com.crm.smartmachine.bean.response.QhBean
import com.crm.smartmachine.contants.EventConstants
import com.crm.smartmachine.databinding.FragmentReceiveBillBinding
import com.crm.smartmachine.event.Message
import com.crm.smartmachine.manager.ModbusManager
import com.crm.smartmachine.manager.callback.WriteRegistersCallback
import com.crm.smartmachine.ui.dialog.ReceiveSuccessDialog
import com.crm.smartmachine.ui.receive.adapter.BillAdapter
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog


/**
 * 申领物品清单
 */
class ReceiveBillFragment : SmartBaseFragment<FragmentReceiveBillBinding>() {

    override fun getLayoutId(): Int? = R.layout.fragment_receive_bill

//    private val viewModel: MainViewModel by viewModel()

    @Param
    private lateinit var qhm: String

    private val billAdapter by lazy { BillAdapter() }

    private lateinit var mSoundPool: SoundPool
    private lateinit var audioAttributes: AudioAttributes
    private var soundStart = 0
    private var soundEnd = 0
    private var qhBean: QhBean? = null
    private var successDialogBuilder: ReceiveSuccessDialog.Builder? = null

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        binding.recyclerView.adapter = billAdapter

        observe()
        onClick()
        requestData()

        // 领取声音提示
        audioAttributes = AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
            .setUsage(AudioAttributes.USAGE_MEDIA)
            .build()

        mSoundPool = SoundPool.Builder()
            .setMaxStreams(3)
            .setAudioAttributes(audioAttributes)
            .build()

        soundStart = mSoundPool.load(mContext.assets.openFd("start.mp3"), 1)
        soundEnd = mSoundPool.load(mContext.assets.openFd("end.mp3"), 1)
    }

    private fun observe() {
        viewModel.errorResponse.observe(this) {
            handleErrorResponse(it)
            hideLoadingDialog()
        }
        //取货物品信息
        viewModel.getSpdByQhmResponse.observe(this) {
            hideLoadingDialog()
            qhBean = it
            billAdapter.setList(it.slwpList)
        }
        viewModel.updateSpdByQhmResponse.observe(this) {
            showSuccessDialog()
        }
        viewModel.updateSpdLqwpWzResponse.observe(this) {
            showSuccessDialog()
        }
    }

    private fun showSuccessDialog() {
        if (successDialogBuilder == null)
            successDialogBuilder = ReceiveSuccessDialog.Builder(mContext)
        successDialogBuilder?.setListener(object : ReceiveSuccessDialog.OnButtonClickListener {
            override fun onBackClick() {
                successDialogBuilder?.dismiss()
                navigateBackHome()
            }

            override fun onContinueClick() {
                successDialogBuilder?.dismiss()
                requestData()
            }
        })?.show()
    }

    private fun onClick() {
        //返回
        binding.actionBarBack.clickNoRepeat {
            viewModel.defUI.msgEvent.postValue(Message(0, EventConstants.START_TIMER))
            navigateBack()
        }
        // 领取
        binding.btnCheckboxSubmit.clickNoRepeat {
            receiveGoods()
        }
    }

    private fun navigateBackHome() {
        navigateBack()
        viewModel.defUI.msgEvent.postValue(Message(0, EventConstants.BACK_HOME))
    }

    private fun receiveGoods() {
        if (billAdapter.data.isEmpty()) {
            toast("暂无要领取的物品")
            return
        }

        qhBean?.let {
            if (it.wpwz == "0") { //开取货口
                toast("wpwz:${it.wpwz}，开取货口")
                mSoundPool.play(soundStart, 1F, 1F, 0, 0, 1F)
                //开取货口
                ModbusManager.openCase4Receive()
                //接口4
                viewModel.updateSpdByQhm(qhm)

//                billAdapter.data.forEach { spd ->
//            ModbusManager.openCase4Receive(spd.wpbh, spd.slsl)
//            var flag = 1
//            while (flag == 1) {
//                ModbusReq.getInstance().readHoldingRegisters(object : OnRequestBack<ShortArray?> {
//                    override fun onSuccess(data: ShortArray?) {
//                        if (data != null) {
//                            if (0 == Integer.parseInt(data[0].toString()) &&
//                                0 == Integer.parseInt(data[1].toString()) &&
//                                0 == Integer.parseInt(data[2].toString())
//                            ) {
//                                mSoundPool.play(soundEnd, 1F, 1F, 0, 0, 1F);
//                                flag = 0
//                            }
//                        }
//                    }
//
//                    override fun onFailed(msg: String) {
//                        toast(("$msg"))
//                    }
//                }, 1, 0, 8)
//                Thread.sleep(500)
//            }

//                }
            } else { //开储物柜
                toast("wpwz:${it.wpwz}，开储物柜")
                ModbusManager.openCase4Save(it.wpwz, object : WriteRegistersCallback {
                    override fun onSuccess() {
                        toast("成功，更新审批单")
//                        //接口14：更新审批单领取物品位置
//                        viewModel.updateSpdLqwpWz(UpdateSpdLqwpWzRequest(it.unid, it.wpwz))

                        //接口4
                        viewModel.updateSpdByQhm(qhm)
                    }
                })

            }
        }

//
//        ReceiveSuccessDialog.Builder(mContext)
//            .setListener(object : ReceiveSuccessDialog.OnButtonClickListener {
//                override fun onBackClick() {
//        viewModel.defUI.msgEvent.postValue(Message(0, EventConstants.START_TIMER))
//                    navigateBack()
//                    viewModel.defUI.msgEvent
//                        .postValue(Message(0, EventConstants.BACK_HOME))
//                }
//
//                override fun onContinueClick() {
//                    requestData()
//                }
//            }).show()

    }

    private fun requestData() {
        showLoadingDialog()
        //接口3
        viewModel.getSpdByQhm(qhm, "N")
    }

    private var loadingDialog: QMUITipDialog? = null

    private fun showLoadingDialog() {
        if (loadingDialog == null) {
            loadingDialog = QMUITipDialog
                .Builder(mContext)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .create()
        }
        loadingDialog?.show()
    }

    private fun hideLoadingDialog() {
        loadingDialog?.dismiss()
    }
}